package com.boarsoft.boar.config.drm.server.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.boarsoft.boar.config.drm.server.DrmConfigServer;

import cn.com.antcloud.api.AntFinTechApiClient;
import cn.com.antcloud.api.AntFinTechProfile;
import cn.com.antcloud.api.ms.v2_0_0.model.CellInfo;
import cn.com.antcloud.api.ms.v2_0_0.model.DrmAttribute;
import cn.com.antcloud.api.ms.v2_0_0.model.DrmDataCellInfo;
import cn.com.antcloud.api.ms.v2_0_0.model.DrmResource;
import cn.com.antcloud.api.ms.v2_0_0.request.AddDrmDrmattributesRequest;
import cn.com.antcloud.api.ms.v2_0_0.request.AddDrmDrmdataRequest;
import cn.com.antcloud.api.ms.v2_0_0.request.AddDrmDrmgraydataRequest;
import cn.com.antcloud.api.ms.v2_0_0.request.AddDrmDrmresourcesRequest;
import cn.com.antcloud.api.ms.v2_0_0.request.GetDrmDrmattributesRequest;
import cn.com.antcloud.api.ms.v2_0_0.request.ListDrmDrmdatacellsRequest;
import cn.com.antcloud.api.ms.v2_0_0.request.QueryDrmDrmresourcesRequest;
import cn.com.antcloud.api.ms.v2_0_0.request.UpdateDrmDrmattributesRequest;
import cn.com.antcloud.api.ms.v2_0_0.request.UpdateDrmDrmresourcesRequest;
import cn.com.antcloud.api.ms.v2_0_0.response.AddDrmDrmattributesResponse;
import cn.com.antcloud.api.ms.v2_0_0.response.AddDrmDrmdataResponse;
import cn.com.antcloud.api.ms.v2_0_0.response.AddDrmDrmgraydataResponse;
import cn.com.antcloud.api.ms.v2_0_0.response.AddDrmDrmresourcesResponse;
import cn.com.antcloud.api.ms.v2_0_0.response.GetDrmDrmattributesResponse;
import cn.com.antcloud.api.ms.v2_0_0.response.ListDrmDrmdatacellsResponse;
import cn.com.antcloud.api.ms.v2_0_0.response.QueryDrmDrmresourcesResponse;
import cn.com.antcloud.api.ms.v2_0_0.response.UpdateDrmDrmattributesResponse;
import cn.com.antcloud.api.ms.v2_0_0.response.UpdateDrmDrmresourcesResponse;

/**
 * 服务端方法实现
 */
@Component("drmConfigServer")
public class DrmConfigServerImpl implements DrmConfigServer {
    @Value("${drm.base.url:http://apigw.cdant.dev.origien.com.cn}")
    private  String baseUrl;
    @Value("${drm.access.key:AC5KnzSXhM6TB4Bh}")
    private String accessKey;

    @Value("${drm.access.secret:ykRzxDSYXWEXFH2vbJxCVJsbgC5SgooK}")
    private String accessSecret;

    @Value("${drm.ver:3.0}")
    private String ver;

    private static final String REGION = "origien";

    private static final String PRODUCT_INSTANCE_ID = "MiddleWareCluster-MS";

    @Override
    public List<DrmResource> getResource(String appName, String instanceId, String resourceId, Long pageNo, Long pageSize) throws InterruptedException {
        // 初始化客⼾端。
        AntFinTechProfile profile = AntFinTechProfile.getProfile(
                baseUrl,
                accessKey,
                accessSecret
                );
        AntFinTechApiClient client = new AntFinTechApiClient(profile);
        // 构建请求。
        QueryDrmDrmresourcesRequest request = new QueryDrmDrmresourcesRequest();
        request.setAppName(appName);
        request.setInstanceId(instanceId);
        request.setKeyword(resourceId);
        request.setPageSize(pageSize);
        request.setStart(pageNo);
        request.setProductInstanceId(PRODUCT_INSTANCE_ID);
        //request.setRegionName("");
        // 发送请求，并且获取响应结果。
        QueryDrmDrmresourcesResponse response = client.execute(request);
        if(response.isSuccess()){
            return response.getDrmResources();
        }
        return null;
    }

    private String getDataId(String appName, String resourceId,String name){
        StringBuilder sb = new StringBuilder();
        sb.append(REGION);
        sb.append(".");
        sb.append(appName);
        sb.append(":name=");
        sb.append(resourceId);
        sb.append(".");
        sb.append(name);
        sb.append(",version=");
        sb.append(ver);
        sb.append("@DRM");
        return sb.toString();
    }
    @Override
    public boolean addResource(String appName, String instanceId, String resourceId, String resourceVersion) throws InterruptedException {
        // 初始化客⼾端。
        AntFinTechProfile profile = AntFinTechProfile.getProfile(
                baseUrl,
                accessKey,
                accessSecret
                );
        AntFinTechApiClient client = new AntFinTechApiClient(profile);
        // 构建请求。
        AddDrmDrmresourcesRequest request = new AddDrmDrmresourcesRequest();
        request.setAppName(appName);
        //request.setAttributes(attributes);
        //request.setId(123);
        request.setInstanceId(instanceId);
        //request.setName("watchmen http test");
        request.setRegion(REGION);
        //request.setResourceDomain("Alipay.dsrconsole");
        request.setResourceId(resourceId);
        request.setResourceVersion(resourceVersion);
        //request.setType("tpl");
        request.setProductInstanceId(PRODUCT_INSTANCE_ID);
        //request.setRegionName("");
        // 发送请求，并且获取响应结果。
        AddDrmDrmresourcesResponse response = client.execute(request);
        if(response.isSuccess()){
            return true;
        }
        return false;
    }

    @Override
    public boolean updateResource(String appName, String instanceId, String resourceId, String resourceVersion) throws InterruptedException {
        // 初始化客⼾端。
        AntFinTechProfile profile = AntFinTechProfile.getProfile(
                baseUrl,
                accessKey,
                accessSecret
                );
        AntFinTechApiClient client = new AntFinTechApiClient(profile);
    // 构建请求。
        UpdateDrmDrmresourcesRequest request = new UpdateDrmDrmresourcesRequest();
        request.setAppName(appName);
        //request.setId(123);
        request.setInstanceId(instanceId);
        //request.setName("name");
        request.setRegion(REGION);
        //request.setResourceDomain("Alipay.dsrconsole");
        request.setResourceId(resourceId);
        request.setResourceVersion(resourceVersion);
        //request.setType("tpl");
        request.setProductInstanceId(PRODUCT_INSTANCE_ID);
        //request.setRegionName("");
    // 发送请求，并获取响应结果。
        UpdateDrmDrmresourcesResponse response = client.execute(request);
        if(response.isSuccess()){
            return true;
        }
        return false;
    }

    @Override
    public DrmAttribute getAttribute(String dataId, String instanceId) throws InterruptedException {
        // 初始化客⼾端。
        AntFinTechProfile profile = AntFinTechProfile.getProfile(
                baseUrl,
                accessKey,
                accessSecret
                );
        AntFinTechApiClient client = new AntFinTechApiClient(profile);
// 构建请求。
        GetDrmDrmattributesRequest request = new GetDrmDrmattributesRequest();
        request.setDataId(dataId);
        request.setInstanceId(instanceId);
        request.setProductInstanceId(PRODUCT_INSTANCE_ID);
        //request.setRegionName("");
// 发送请求，并且获取响应结果。
        GetDrmDrmattributesResponse response = client.execute(request);
        if (response.isSuccess()){
            return response.getDrmAttribute();
        }
        return null;
    }

    @Override
    public boolean addAttribute(String attrName, String instanceId, Long parentId) throws InterruptedException {
        // 初始化客⼾端。
        AntFinTechProfile profile = AntFinTechProfile.getProfile(baseUrl,accessKey,accessSecret);
        AntFinTechApiClient client = new AntFinTechApiClient(profile);
        // 构建请求。
        AddDrmDrmattributesRequest request = new AddDrmDrmattributesRequest();
        request.setAttributeName(attrName);
        request.setInstanceId(instanceId);
        request.setParentId(parentId);
        request.setProductInstanceId(PRODUCT_INSTANCE_ID);
        // 发送请求，并且获取响应结果。
        AddDrmDrmattributesResponse response = client.execute(request);
        if(!response.isSuccess()){
            return false;
        }
        return true;
    }

    @Override
    public boolean updateAttribute(String attrName, String instanceId, Long parentId) throws InterruptedException {
        // 初始化客⼾端。
        AntFinTechProfile profile = AntFinTechProfile.getProfile(baseUrl,accessKey,accessSecret);
        AntFinTechApiClient client = new AntFinTechApiClient(profile);
// 构建请求。
        UpdateDrmDrmattributesRequest request = new UpdateDrmDrmattributesRequest();
        request.setAttributeName(attrName);
        request.setInstanceId(instanceId);
        request.setParentId(parentId);
        request.setProductInstanceId(PRODUCT_INSTANCE_ID);
        request.setRegionName("");
// 发送请求，并且获取响应结果。
        UpdateDrmDrmattributesResponse response = client.execute(request);
        if(!response.isSuccess()){
            return false;
        }
        return true;
    }

    @Override
    public boolean pushDrmdata(String dataId, String instanceId, String pushCells, String value) throws InterruptedException {
        // 初始化客⼾端。
        AntFinTechProfile profile = AntFinTechProfile.getProfile(baseUrl,accessKey,accessSecret);
        //构建请求
        AddDrmDrmdataRequest request = new AddDrmDrmdataRequest();
        request.setDataId(dataId);
        AntFinTechApiClient client = new AntFinTechApiClient(profile);
        request.setInstanceId(instanceId);
        if(StringUtils.isEmpty(pushCells)) {
            //推送所有单元
            request.setPushTargetType("ALL");
            //request.setPushCells(pushCells);
        }else {
            //推送指定单元
            request.setPushCells(pushCells);
            request.setPushTargetType("PART");
        }
        request.setValue(value);
        request.setProductInstanceId(PRODUCT_INSTANCE_ID);
        request.setRegionName(REGION);
        // 发送请求，并且获取响应结果
        AddDrmDrmdataResponse response = client.execute(request);
        if(!response.isSuccess()){
            throw new RuntimeException("配置推送失败,name ={"+pushCells+"}");
        }
        return true;
    }

    /**
     * 灰度推送
     * @param dataId
     * @param instanceId
     * @param hosts
     * @param value
     * @return
     * @throws InterruptedException
     */
    @Override
    public boolean pushGrayDrmdata(String dataId, String instanceId, String hosts, String value) throws InterruptedException {
        // 初始化客⼾端。
        AntFinTechProfile profile = AntFinTechProfile.getProfile(baseUrl,accessKey,accessSecret);
        AntFinTechApiClient client = new AntFinTechApiClient(profile);
        // 构建请求。
        AddDrmDrmgraydataRequest request = new AddDrmDrmgraydataRequest();
        request.setDataId(dataId);
        request.setHosts(hosts);
        request.setInstanceId(instanceId);
        request.setValue(value);
        request.setProductInstanceId(PRODUCT_INSTANCE_ID);
        // 发送请求，并且获取响应结果。
        AddDrmDrmgraydataResponse response = client.execute(request);
        if(!response.isSuccess()){
            throw new RuntimeException("配置推送失败,hosts ={"+hosts+"}");
        }
        return true;
    }

    /**
     * 获取推送值
     * @param instanceId
     * @return
     * @throws InterruptedException
     */
    @Override
    public DrmDataCellInfo getDataCellInfo(String instanceId, String dataId) throws InterruptedException {
        // 初始化客戶端
        AntFinTechProfile profile = AntFinTechProfile.getProfile(
                baseUrl,accessKey,accessSecret
        );
        AntFinTechApiClient client = new AntFinTechApiClient(profile);
        // 构建请求
        ListDrmDrmdatacellsRequest request = new ListDrmDrmdatacellsRequest();
        if(!StringUtils.isEmpty(dataId)) {
            request.setDataId(dataId);
        }
        request.setInstanceId(instanceId);
        request.setProductInstanceId(PRODUCT_INSTANCE_ID);
        // 发送请求，并且获取响应结果
        ListDrmDrmdatacellsResponse response = client.execute(request);
        if(response.isSuccess()){
            return response.getDrmDataCellInfo();
        }
        return null;
    }

    /**
     * 推送值
     * @param name
     * @param value
     * @param instanceId
     * @param resourceId
     * @param appName
     * @throws InterruptedException
     */
    @Override
    public void pushValue(String name, String value, String instanceId, String resourceId, String appName) throws InterruptedException {
        try {
            //查询resource
            List<DrmResource> resources = this.getResource(appName, instanceId, resourceId, 1L, 1000L);
            if (CollectionUtils.isEmpty(resources)) {
                if (!this.addResource(appName, instanceId, resourceId, "1.0")) {
                    return;
                }
            }
            resources = this.getResource(appName, instanceId, resourceId, 1L, 1000L);
            Long id = resources.get(0).getId();
            //获取dataId
            String dataId = this.getDataId(appName,resourceId,name);
            DrmAttribute attribute = this.getAttribute(dataId, instanceId);
            if (null == attribute) {
                //添加变量
                if(!this.addAttribute(name, instanceId, id)) {
                    throw new InterruptedException("添加变量属性失败");
                }
            }
            //推送drm配置
            if(!this.pushDrmdata(dataId, instanceId, null, value)){
                throw new InterruptedException("推送变量值失败");
            }
        } catch(Throwable e){
            throw new InterruptedException("推送变量失败,"+e.getMessage());
        }
    }

    /**
     * 从drm拉取实例下单个配置
     * @param appName 应用名称
     * @param instanceId 实例名称
     * @param resourceId 资源id
     * @param name 属性名称
     * @return 属性值
     * @throws InterruptedException
     */
    @Override
    public String pullValue(String appName, String instanceId, String resourceId, String name) throws InterruptedException {
        String dataId = this.getDataId(appName,resourceId,name);
        DrmDataCellInfo drmDataCellInfos = getDataCellInfo(instanceId, dataId);
        List<CellInfo> cellInfos= drmDataCellInfos.getCellInfos();
        if(CollectionUtils.isEmpty(cellInfos)){
            return "";
        }
        return cellInfos.get(0).getValue();
    }

    /**
     * 从drm拉取实例下所有属性
     * @param appName 应用名称
     * @param instanceId 实例名称
     * @param resourceId 资源id
     * @return  属性列表
     */
    @Override
    public Map<String,Object> pullAll(String appName, String instanceId, String resourceId) throws InterruptedException {
        //String dataId = this.getDataId(appName,resourceId,"ALL");
        //查询resource
        List<DrmResource> resources = this.getResource(appName, instanceId, resourceId, 1L, 1000L);
        if(CollectionUtils.isEmpty(resources)){
            return null;
        }
        Map<String,Object> mapv = new HashMap<>();
        for (int i = 0; i < resources.size(); i++) {
            DrmResource resource = resources.get(i);
            if(!resourceId.equals(resource.getResourceId())){
                continue;
            }
            List<DrmAttribute> attributes = resource.getAttributes();
            for (DrmAttribute attribute : attributes) {
                String attributeName = attribute.getAttributeName();
                String dataId = this.getDataId(appName,resourceId,attributeName);
                DrmDataCellInfo drmDataCellInfos = null;
                try {
                    drmDataCellInfos = getDataCellInfo(instanceId, dataId);
                } catch (InterruptedException e) {
                    continue;
                }
                List<CellInfo> cellInfos= drmDataCellInfos.getCellInfos();
                mapv.put(attributeName,cellInfos.get(0).getValue());
            }
        }
        return  mapv;
    }
}

